<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><link rel=manifest href=/manifest.json>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#fff">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />














  
  
    
  
  <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Comic Neue:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/icons/icon-72x72.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/icons/icon-72x72.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#fff">


  <link rel="manifest" href="/images/manifest.json">


  <meta name="msapplication-config" content="/images/browserconfig.xml" />



  <meta name="keywords" content="算法,面试," />





  <link rel="alternate" href="/atom.xml" title="Awebone's Blog" type="application/atom+xml" />






<meta name="description" content="本文使用多种计算引擎实现词频统计

MapReduce实现编写MapReduce程序分成三部分：Mapper、Reducer、Driver
业务逻辑

MapTask阶段处理每个数据分块的单词统计分析，每遇到一个单词，将其转换为一个k-v对，如&amp;lt;hello, 1&amp;gt;的形式，发送给ReduceTask进行汇总
ReduceTask阶段接受MapTask的结果，做汇总计数

Mapper接">
<meta property="og:type" content="article">
<meta property="og:title" content="多种计算引擎实现WordCount">
<meta property="og:url" content="https://www.awebone.com/posts/dd22b276/index.html">
<meta property="og:site_name" content="Awebone's Blog">
<meta property="og:description" content="本文使用多种计算引擎实现词频统计

MapReduce实现编写MapReduce程序分成三部分：Mapper、Reducer、Driver
业务逻辑

MapTask阶段处理每个数据分块的单词统计分析，每遇到一个单词，将其转换为一个k-v对，如&amp;lt;hello, 1&amp;gt;的形式，发送给ReduceTask进行汇总
ReduceTask阶段接受MapTask的结果，做汇总计数

Mapper接">
<meta property="og:updated_time" content="2020-07-18T08:37:20.775Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="多种计算引擎实现WordCount">
<meta name="twitter:description" content="本文使用多种计算引擎实现词频统计

MapReduce实现编写MapReduce程序分成三部分：Mapper、Reducer、Driver
业务逻辑

MapTask阶段处理每个数据分块的单词统计分析，每遇到一个单词，将其转换为一个k-v对，如&amp;lt;hello, 1&amp;gt;的形式，发送给ReduceTask进行汇总
ReduceTask阶段接受MapTask的结果，做汇总计数

Mapper接">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.awebone.com/posts/dd22b276/"/>





  <title>多种计算引擎实现WordCount | Awebone's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/xuyanbo03" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Awebone's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">见多方能识广，进而才可以融会贯通；取他人之所长，谦而才可以为我所用。</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-top">
          <a href="/top/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-signal"></i> <br />
            
            阅读排行
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.awebone.com/posts/dd22b276/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Awebone">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/icons/icon-144x144.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Awebone's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">多种计算引擎实现WordCount</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-03-26T15:00:00+08:00">
                2020-03-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/大数据/" itemprop="url" rel="index">
                    <span itemprop="name">大数据</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/dd22b276/" class="leancloud_visitors" data-flag-title="多种计算引擎实现WordCount">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
                 <span>℃</span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,312
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本文使用多种计算引擎实现词频统计</p>
</blockquote>
<h1 id="MapReduce实现"><a href="#MapReduce实现" class="headerlink" title="MapReduce实现"></a>MapReduce实现</h1><p>编写MapReduce程序分成三部分：<code>Mapper</code>、<code>Reducer</code>、<code>Driver</code></p>
<p><strong>业务逻辑</strong></p>
<ol>
<li><code>MapTask</code>阶段处理每个数据分块的单词统计分析，每遇到一个单词，将其转换为一个<code>k-v</code>对，如<code>&lt;hello, 1&gt;</code>的形式，发送给<code>ReduceTask</code>进行汇总</li>
<li><code>ReduceTask</code>阶段接受<code>MapTask</code>的结果，做汇总计数</li>
</ol>
<p><strong>Mapper接受的四个泛型</strong></p>
<ul>
<li><code>KEYIN</code>：输入的键的类型，在这里指的是每一行起始的偏移量</li>
<li><code>VALUEIN</code>：输入的值的类型，在这里指的是一行的内容</li>
<li><code>KEYOUT</code>：输出的键的类型，这里指的是单词，允许重复的</li>
<li><code>VALUEOUT</code>：输出的值的类型</li>
</ul>
<a id="more"></a>
<p><strong>Reducer接受的四个泛型</strong></p>
<ul>
<li><code>KEYIN</code>：map输出的key，指的就是单词</li>
<li><p><code>VALUEIN</code>：map输出的value，指的就是1</p>
</li>
<li><p><code>KEYOUT</code>：输出的key的类型，这里指的就是单词，这里的key不可以重复</p>
</li>
<li><code>VALUEOUT</code>：输出的value的类型，这里指的就是总的词频</li>
</ul>
<p><strong>Hadoop中自定义的序列化和反序列化的接口</strong></p>
<p>Java中的序列化和反序列化接口Serializable，将类结构一并进行序列化和反序列化，过于臃肿</p>
<ul>
<li><code>long——LongWritable</code></li>
<li><code>int——IntWritable</code></li>
<li><code>double——DoubleWritable</code></li>
<li><code>float——FloatWritable</code></li>
<li><code>null——NullWritable</code></li>
<li><code>string——Text</code></li>
</ul>
<p><strong>Map实现</strong></p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">WordCountMapper</span> <span class="keyword">extends</span> <span class="title">Mapper</span>&lt;<span class="title">LongWritable</span>, <span class="title">Text</span>, <span class="title">Text</span>, <span class="title">IntWritable</span>&gt;</span>{</div><div class="line">	<span class="comment">/**</span></div><div class="line">	 * 这个方法的调用频率：每行调用一次,文本中有几行就调用几次</div><div class="line">	 * key:当前行的起始偏移量</div><div class="line">	 * value:当前行的内容,和key是一一对应的</div><div class="line">	 */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">map</span><span class="params">(LongWritable key,</span></span></div><div class="line">			Text value, </div><div class="line">			Context context)</div><div class="line">			<span class="keyword">throws</span> IOException, InterruptedException {</div><div class="line">		<span class="comment">//拿到每一行的内容  进行分割  </span></div><div class="line">		<span class="comment">//将text---String</span></div><div class="line">		String line = value.toString();</div><div class="line">		<span class="comment">//拆分单词</span></div><div class="line">		String[] words = line.split(<span class="string">"\t"</span>);</div><div class="line">		<span class="comment">//循环遍历每一个单词  进行打标机  1  发送给reduce进行统一统计</span></div><div class="line">		<span class="keyword">for</span>(String w:words){</div><div class="line">			<span class="comment">//参数1：key   参数2：value</span></div><div class="line">			<span class="comment">//String--text</span></div><div class="line">			Text k=<span class="keyword">new</span> Text(w);</div><div class="line">			IntWritable v=<span class="keyword">new</span> IntWritable(<span class="number">1</span>);</div><div class="line">			context.write(k, v);</div><div class="line">		}</div><div class="line">	}</div><div class="line">}</div></pre></td></tr></tbody></table></figure>
<p><strong>Reduce实现</strong></p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">WordCountReducer</span> <span class="keyword">extends</span> <span class="title">Reducer</span>&lt;<span class="title">Text</span>, <span class="title">IntWritable</span>, <span class="title">Text</span>, <span class="title">IntWritable</span>&gt;</span>{</div><div class="line">	<span class="comment">/**</span></div><div class="line">	 * 这个方法的调用频率：每组调用一次</div><div class="line">	 * 分组规则：key相同的为一组</div><div class="line">	 * key:reduce输入的,这里指的是单词,每一组中的一个key</div><div class="line">	 * values:每一组中的所有value,&lt;1,1,1&gt;</div><div class="line">	 */</div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">reduce</span><span class="params">(Text key, </span></span></div><div class="line">			Iterable&lt;IntWritable&gt; values,</div><div class="line">			Context context) <span class="keyword">throws</span> IOException, InterruptedException {</div><div class="line">		<span class="comment">//进行词频统计</span></div><div class="line">		<span class="keyword">int</span> sum=<span class="number">0</span>;</div><div class="line">		<span class="comment">//循环变遍历values   求和</span></div><div class="line">		<span class="keyword">for</span>(IntWritable v:values){</div><div class="line">			<span class="comment">//v.get()  这个是将intwritable转换为int</span></div><div class="line">			sum+=v.get();</div><div class="line">		}</div><div class="line">		context.write(key, <span class="keyword">new</span> IntWritable(sum));</div><div class="line">	}</div><div class="line">}</div></pre></td></tr></tbody></table></figure>
<p><strong>Driver实现</strong></p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Driver</span> </span>{</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span></div><div class="line">        <span class="keyword">throws</span> IOException, ClassNotFoundException, InterruptedException {</div><div class="line">		System.setProperty(<span class="string">"HADOOP_USER_NAME"</span>, <span class="string">"hadoop"</span>);</div><div class="line">		<span class="comment">//加载配置文件</span></div><div class="line">		Configuration conf=<span class="keyword">new</span> Configuration();</div><div class="line">		<span class="comment">//启动一个job：一个map reduce程序，这里叫做一个job</span></div><div class="line">		Job job=Job.getInstance(conf);</div><div class="line">		</div><div class="line">		<span class="comment">//ָ指定job运行的主类</span></div><div class="line">		job.setJarByClass(Driver.class);</div><div class="line">		</div><div class="line">		<span class="comment">//指定这个job的mapper类和reduce类</span></div><div class="line">		job.setMapperClass(WordCountMapper.class);</div><div class="line">		job.setReducerClass(WordCountReducer.class);</div><div class="line">		</div><div class="line">		<span class="comment">//指定map的输出的key和value的类型</span></div><div class="line">		<span class="comment">//这里为什么还要指定：泛型的只在编译的时候有作用，运行会自动擦除，所以在这里需要指定一下</span></div><div class="line">		job.setMapOutputKeyClass(Text.class);</div><div class="line">		job.setMapOutputValueClass(IntWritable.class);</div><div class="line">		</div><div class="line">		<span class="comment">//指定reduce输出的key和value类型</span></div><div class="line">		job.setOutputKeyClass(Text.class);</div><div class="line">		job.setOutputValueClass(IntWritable.class);</div><div class="line">		</div><div class="line">		<span class="comment">//指定combiner组件</span></div><div class="line">		<span class="comment">//job.setCombinerClass(WordCountReducer.class);</span></div><div class="line">		<span class="comment">//添加自定义分区</span></div><div class="line">		<span class="comment">//job.setPartitionerClass(MyPartitioner.class);</span></div><div class="line">		<span class="comment">// 这个参数如果不指定,默认reducetask=1</span></div><div class="line">		job.setNumReduceTasks(<span class="number">4</span>);</div><div class="line">	</div><div class="line">        <span class="comment">//传参方式</span></div><div class="line">		<span class="comment">//FileInputFormat.addInputPath(job, new Path(args[0]));</span></div><div class="line">		<span class="comment">//添加输出路径：输出路径一定不能存在，怕如果存在会进行覆盖</span></div><div class="line">		<span class="comment">//FileOutputFormat.setOutputPath(job, new Path(args[1]));</span></div><div class="line">        </div><div class="line">        <span class="comment">//固定写死</span></div><div class="line">		FileInputFormat.addInputPath(job, <span class="keyword">new</span> Path(<span class="string">"hdfs://hadoop01:9000/in"</span>));</div><div class="line">		FileOutputFormat.setOutputPath(job, <span class="keyword">new</span> Path(<span class="string">"hdfs://hadoop01:9000/out"</span>));</div><div class="line">		<span class="comment">//提交job</span></div><div class="line">		job.waitForCompletion(<span class="keyword">true</span>);</div><div class="line">	}</div><div class="line">}</div></pre></td></tr></tbody></table></figure>
<p><br></p>
<h1 id="Scala实现"><a href="#Scala实现" class="headerlink" title="Scala实现"></a>Scala实现</h1><p>定义数据：<code>array = Array("a b", "c c", "b c")</code></p>
<h2 id="第一种方式实现"><a href="#第一种方式实现" class="headerlink" title="第一种方式实现"></a>第一种方式实现</h2><figure class="highlight scala"><table><tbody><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">val</span> countWord = array.flatMap(_.split(<span class="string">" "</span>))</div><div class="line">	.map((_,<span class="number">1</span>))</div><div class="line">	.groupBy(_._1)</div><div class="line">	.map( x =&gt; (x._1, x._2.length))</div><div class="line">	.toList</div><div class="line">	.sortBy(_._2)</div><div class="line">	.reverse</div></pre></td></tr></tbody></table></figure>
<p><strong>中间结果详解</strong></p>
<ul>
<li><code>array.map(_.split(" "))</code>输出：<code>Array(Array("a","b"), Array("c","c"), Array("b","c"))</code></li>
<li>使用<code>flatMap(_.split(" "))</code>输出：<code>Array("a","b", "c","c", "b","c")</code></li>
<li>再使用<code>map((_,1))</code>输出：<code>Array((a,1), (b,1), (c,1), (c,1), (b,1), (c,1))</code></li>
<li>再使用<code>groupBy(_._1)</code>输出：<code>(a,1)，(b,1)，(b,1)，(c,1)，(c,1)，(c,1)</code>，即<code>Map(b -&gt; Array((b,1), (b,1)), a -&gt; Array((a,1)), c -&gt; Array((c,1), (c,1), (c,1)))</code></li>
<li>在进行计数：<code>array.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).map( x =&gt; (x._1, x._2.length))</code></li>
<li>从大到小排序：<code>array.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).map( x =&gt; (x._1, x._2.length)).toList.sortBy(_._2).reverse</code></li>
</ul>
<h2 id="其他方式实现"><a href="#其他方式实现" class="headerlink" title="其他方式实现"></a>其他方式实现</h2><figure class="highlight scala"><table><tbody><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">val</span> countWord1 = array.map(_.split(<span class="string">" "</span>))</div><div class="line">	.flatten</div><div class="line">	.map((_,<span class="number">1</span>))</div><div class="line">	.groupBy(_._1)</div><div class="line">	.map(t =&gt; (t._1,t._2.size))</div><div class="line">	.toList</div><div class="line">	.sortBy(_._2)</div><div class="line">	.reverse</div><div class="line"></div><div class="line"><span class="keyword">val</span> countWord2 = array.flatMap(_.split(<span class="string">" "</span>))</div><div class="line">	.map((_,<span class="number">1</span>))</div><div class="line">	.groupBy(_._1)</div><div class="line">	.mapValues(_.size)</div><div class="line">	.toList</div><div class="line">	.sortBy(_._2)</div><div class="line">	.reverse</div><div class="line"></div><div class="line"><span class="keyword">val</span> countWord3 = array.flatMap(_.split(<span class="string">" "</span>))</div><div class="line">	.map((_,<span class="number">1</span>))</div><div class="line">	.groupBy(_._1)</div><div class="line">	.mapValues(_.foldLeft(<span class="number">0</span>)(_+_._2))</div><div class="line">	.toList</div><div class="line">	.sortBy(_._2)</div><div class="line">	.reverse</div></pre></td></tr></tbody></table></figure>
<p><br></p>
<h1 id="Spark-Shell实现"><a href="#Spark-Shell实现" class="headerlink" title="Spark-Shell实现"></a>Spark-Shell实现</h1><h2 id="第一种方式实现-1"><a href="#第一种方式实现-1" class="headerlink" title="第一种方式实现"></a>第一种方式实现</h2><figure class="highlight scala"><table><tbody><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">sc.textFile(<span class="string">"hdfs://myha/spark/wc/input/words.txt"</span>)</div><div class="line">	.flatMap(_.split(<span class="string">" "</span>))</div><div class="line">	.map((_, <span class="number">1</span>))</div><div class="line">	.reduceByKey(_+_)</div><div class="line">	.collect</div></pre></td></tr></tbody></table></figure>
<p><strong>详解</strong></p>
<ul>
<li><code>sc</code>是<code>SparkContext</code>对象，该对象是提交<code>spark</code>程序的入口</li>
<li><code>textFile("hdfs://myha/spark/wc/input/words.txt")</code>是从<code>HDFS</code>中读取数据</li>
<li><code>flatMap(_.split(" "))</code>先<code>map</code>再压平</li>
<li><code>map((_,1))</code>将单词和1构成元组</li>
<li><code>reduceByKey(_+_)</code>按照<code>key</code>进行<code>reduce</code>，并将<code>value</code>累加</li>
<li><code>saveAsTextFile("hdfs://myha/spark/wc/output")</code>将结果写入到<code>HDFS</code>中</li>
<li>其中：<code>reduceByKey =  groupByKey + reduce = groupBy +  reduce =  groupBy + map</code></li>
</ul>
<h2 id="其他方式实现-1"><a href="#其他方式实现-1" class="headerlink" title="其他方式实现"></a>其他方式实现</h2><figure class="highlight scala"><table><tbody><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">sc.textFile(<span class="string">"hdfs://myha/spark/wc/input/words.txt"</span>)</div><div class="line">	.flatMap(_.split(<span class="string">" "</span>))</div><div class="line">	.map((_,<span class="number">1</span>))</div><div class="line">	.reduceByKey(_+_)</div><div class="line">	.collect</div><div class="line">	.foreach(println)</div><div class="line"></div><div class="line">sc.textFile(<span class="string">"hdfs://myha/spark/wc/input/words.txt"</span>)</div><div class="line">	.flatMap(_.split(<span class="string">" "</span>))</div><div class="line">	.countByValue</div><div class="line">	.foreach(println)</div><div class="line"></div><div class="line">sc.textFile(<span class="string">"hdfs://myha/spark/wc/input/words.txt"</span>)</div><div class="line">	.flatMap(_.split(<span class="string">" "</span>))</div><div class="line">	.map((_,<span class="number">1</span>))</div><div class="line">	.countByKey()</div><div class="line">	.foreach(println)</div></pre></td></tr></tbody></table></figure>
<script>
        document.querySelectorAll('.github-emoji')
          .forEach(el => {
            if (!el.dataset.src) { return; }
            const img = document.createElement('img');
            img.style = 'display:none !important;';
            img.src = el.dataset.src;
            img.addEventListener('error', () => {
              img.remove();
              el.style.color = 'inherit';
              el.style.backgroundImage = 'none';
              el.style.background = 'none';
            });
            img.addEventListener('load', () => {
              img.remove();
            });
            document.body.appendChild(img);
          });
      </script>
      
    </div>
    
    
    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/posts/dd22b276/">多种计算引擎实现WordCount</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Awebone 的个人博客">Awebone</a></p>
  <p><span>发布时间:</span>2020年03月26日 - 15:03</p>
  <p><span>最后更新:</span>2020年07月18日 - 16:07</p>
  <p><span>原始链接:</span><a href="/posts/dd22b276/" title="多种计算引擎实现WordCount">https://www.awebone.com/posts/dd22b276/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://www.awebone.com/posts/dd22b276/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

      
    </div>

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wepay.svg" alt="Awebone 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/算法/" rel="tag"><i class="fa fa-tag"></i> 算法</a>
          
            <a href="/tags/面试/" rel="tag"><i class="fa fa-tag"></i> 面试</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/86ceb8f1/" rel="next" title="Java单例模式">
                <i class="fa fa-chevron-left"></i> Java单例模式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/1d6a9c79/" rel="prev" title="Hadoop面经总结">
                Hadoop面经总结 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/icons/icon-144x144.png"
                alt="Awebone" />
            
              <p class="site-author-name" itemprop="name">Awebone</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">35</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xuyanbo03" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://segmentfault.com/u/awebone" target="_blank" title="Segmentfault">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>Segmentfault</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/awebone" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-spinner"></i>码云</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="xuyanbo03@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-globe"></i>
                友链
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://juejin.im/user/57f916bf128fe100545db838" title="掘金" target="_blank">掘金</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://my.oschina.net/xxyb" title="开源中国" target="_blank">开源中国</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.gitmemory.com/xuyanbo03" title="gitmemory" target="_blank">gitmemory</a>
                  </li>
                
              </ul>
              
<div id="days"></div>
<script>
function show_date_time(){
    window.setTimeout("show_date_time()", 1000);
    BirthDay=new Date("12/09/2016 15:13:14");
    today=new Date();
    timeold=(today.getTime()-BirthDay.getTime());
    sectimeold=timeold/1000
    secondsold=Math.floor(sectimeold);
    msPerDay=24*60*60*1000
    e_daysold=timeold/msPerDay
    daysold=Math.floor(e_daysold);
    e_hrsold=(e_daysold-daysold)*24;
    hrsold=setzero(Math.floor(e_hrsold));
    e_minsold=(e_hrsold-hrsold)*60;
    minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
    seconds=setzero(Math.floor((e_minsold-minsold)*60));
    document.getElementById('days').innerHTML="已运行 "+daysold+" 天 "+hrsold+" 小时 "+minsold+" 分 "+seconds+" 秒";
}
function setzero(i) {
    if (i<10) {
        i="0" + i
    };
    return i;
}
show_date_time();
</script>

<style>
#days {
    display: block;
    color: rgb(7, 179, 155);
    font-size: 13px;
    margin-top: 15px;
}
</style>
            </div>
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#MapReduce实现"><span class="nav-number">1.</span> <span class="nav-text">MapReduce实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Scala实现"><span class="nav-number">2.</span> <span class="nav-text">Scala实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#第一种方式实现"><span class="nav-number">2.1.</span> <span class="nav-text">第一种方式实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他方式实现"><span class="nav-number">2.2.</span> <span class="nav-text">其他方式实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Spark-Shell实现"><span class="nav-number">3.</span> <span class="nav-text">Spark-Shell实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#第一种方式实现-1"><span class="nav-number">3.1.</span> <span class="nav-text">第一种方式实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他方式实现-1"><span class="nav-number">3.2.</span> <span class="nav-text">其他方式实现</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script> 
<div class="copyright">&copy; 2016 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love" id="heart">
    <i class="fa fa-heart aria-hidden="true"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Awebone.com&nbsp;版权所有&nbsp;ICP证：<a href="https://beian.miit.gov.cn">蒙ICP备20000954号-1</a></span>
  <!--
  <span class="author" itemprop="copyrightHolder">Awebone</span>
  -->
<!--
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">50.8k</span>
  
-->
</div>

<!--





-->



<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共50.8k字&nbsp;|&nbsp;</span>
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>人&nbsp;|&nbsp;
</span>
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
</div>

<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，订阅本博客</div>
    </div>
  </div>
</div>

<!--
<div>
  <span>ICP证：<a href="beian.miit.gov.cn">蒙ICP备20000954号</a></span>
</div>
-->
        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.bootcss.com/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("LSAm57bISKEqVJ5qzIteKcXP-gzGzoHsz", "8IMLXHLadeWT8gK336u2foXT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  

  

<script>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js?t=1614270256242')
    .then(function () {console.log('ServiceWorker Register Successfully.')})
    .catch(function (e) {console.error(e)});
}
</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>